package com.ruge.test.springMVC.shiro;

import com.ruge.test.commons.dbutils.SysUser;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * 创建人 ：爱丽丝、如歌
 * 创建时间 ：2018-07-03  21:13
 * 描述 ：
 */
public class demo01_04_01自定义Realm extends AuthorizingRealm {
    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String userName = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials()); //得到密码
        SimpleAuthenticationInfo info = null;
        try {
            String passWord = getPassWordByUserName(userName);
            if (passWord == null) {
                return null;
            }
            if (!passWord.equals(password)) {
                throw new IncorrectCredentialsException(); //如果密码错误
            }
            info = new SimpleAuthenticationInfo(userName, password.trim(), getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return info;
    }

    private String getPassWordByUserName(String userName) throws Exception {
        String res;
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ruge_security?serverTimezone=UTC&useSSL=true", "root", "root");
        QueryRunner runner = new QueryRunner();
        Object[] params = {userName};
        SysUser query = runner.query(conn, "select * from sys_user where user_mobile = ?", new BeanHandler<SysUser>(SysUser.class), params);
        res = query.getPass_Word();
        DbUtils.close(conn);
        return res;
    }
}
